/**
 * ZenUI
 * @module ZenUI
 *
 */
import "./ZenModal.css";

/**
 * @namespace ZenModal
 * @example
 * StateApi.updateStoreState('ZenModal',);
 * @type {Object}
 */
let ZenModal = {
    indexCount: 3,
    modalList: [],
    closeIcon: function(props) {
        return (
            <svg
                id="\u56FE\u5C42_1"
                data-name="\u56FE\u5C42 1"
                xmlns="http://www.w3.org/2000/svg"
                viewBox="0 0 64 64"
                fill="currentColor"
                className="h-icons-icon h-icons-normal"
                style={{
                    width: "17.52px",
                    height: "17.52px",
                    color: "rgb(150, 150, 150)",
                    verticalAlign: "top"
                }}
                onClick={props.cb}
            >
                <defs />
                <rect
                    className="cls-1"
                    x="30.5"
                    y="3.51"
                    width="4"
                    height="57.98"
                    rx="1"
                    ry="1"
                    transform="rotate(-45 32.501 32.498)"
                />
                <rect
                    className="cls-1"
                    x="3.51"
                    y="30.5"
                    width="57.98"
                    height="4"
                    rx="1"
                    ry="1"
                    transform="rotate(-45 32.501 32.498)"
                />
            </svg>
        );
    },
    checkIfHadActiveModal: function(modalList) {
        let hadActive = false;
        Uts.each(modalList, function(item, index) {
            if (item.isShow) {
                hadActive = true;
                Uts.pauseEach = true;
            }
        });
        return hadActive;
    },
    createModal: function(options) {},
    modalDefaultFooter: function(props) {
        const [footerState, updateFooterState] = usePartState({});
        const item = props.item;
        function updateState(value) {
            // console.log("call updateState");
            updateFooterState(value);
        }
        item.passFC({ footer: updateState });
        return (
            <div>
                <div
                    className={Uts.sc([
                        "h-button-button h-button-primary h-modal-conBtn",
                        footerState.okClass
                    ])}
                    type="button"
                    onClick={() => {
                        item.close && item.close(item.getParams() || 1);
                    }}
                >
                    确认
                </div>
                <div
                    className={Uts.sc([
                        "h-button-button h-button-origin h-button-sub h-modal-canBtn",
                        footerState.cancelClass
                    ])}
                    role="button"
                    type="button"
                    onClick={() => {
                        item.close && item.close();
                    }}
                >
                    取消
                </div>
                {Uts.isFunction(item.footer) ? <item.footer /> : item.footer}
            </div>
        );
    },
    initModal: function(options) {
        const state = useStoreState("zenModalConfig", null, {
            modalList: []
        });

        const { modalList } = state;
        return (
            <div
                className={Uts.sc([
                    "zenModalWrap",
                    ZenModal.checkIfHadActiveModal(modalList) ? "" : "zen_hide"
                ])}
            >
                {modalList.map((item, index) => {
                    return (
                        <div key={item.$$index}>
                            <div
                                className={Uts.sc([
                                    "zenModalWrap-backdrop",
                                    item.isShow && !item.hideBackdrop
                                        ? ""
                                        : "zen_hide",
                                    item.backDropClass
                                ])}
                                onClick={() => {
                                    item.closeByBackDrop &&
                                        item.close &&
                                        item.close();
                                }}
                            />
                            <div
                                className={Uts.sc([
                                    "zenModal-float",
                                    item.isShow ? "" : "zen_hide",
                                    !item.withoutShadow
                                        ? "zenModal-shadow"
                                        : "",
                                    "zenModal-key-" + item.$$index,
                                    "zenModal_" + item.size,
                                    item.modalClass
                                ])}
                            >
                                <div className="zen_ps-re">
                                    {!item.hideHeader && (
                                        <div className="zenModal-header">
                                            <div className="zenModal-cancel">
                                                <ZenModal.closeIcon
                                                    cb={() => {
                                                        item.close &&
                                                            item.close();
                                                    }}
                                                />
                                            </div>
                                            {Uts.isFunction(item.header) ? (
                                                <item.header />
                                            ) : (
                                                item.header
                                            )}
                                        </div>
                                    )}
                                    <div className="zenModal-content">
                                        {Uts.isFunction(item.content) ? (
                                            <item.content item={item} />
                                        ) : (
                                            item.content
                                        )}
                                    </div>
                                    {!item.hideFooter && (
                                        <div className="zenModal-footer">
                                            <ZenModal.modalDefaultFooter
                                                item={item}
                                            />
                                        </div>
                                    )}
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>
        );
    },
    /**
     * loadModal
     * @param  {object} options 
     * [header]/[footer]/content:string or component,
     * [size]:large/md/sm,
     * [modalClass]:the class to add to modal itself
     * [backDropClass]:the backdrop class
     * close:the function to close modal,
     * [cbList]:callback list to use,
     * [hideHeader]/[hideFooter]:to hide header or footer,
     * [hideBackdrop]:if hide backdrop,
     * [withoutShadow]:remove modal shadow,
     * [closeByBackDrop]:if close by click back drop,
     * //in component pass in option
     * props.item.passParams("abc");//chang the params when click ok
            React.useEffect(() => {
                //change the footer button class
                props.item.changeFooterClass({
                    okClass: "testOk",
                    cancelClass: "testCancel"
                });
            });
     * @return {object} modal object ,with show/hide/remove method.
     * @example
     function closeModal(value) {
            modal.hide();
        }

     function Content(props) {
         //chang the params when click ok
         props.item.passParams("abc");
         //change the footer button class
         React.useEffect(() => {
             props.item.changeFooterClass({
                 okClass: "testOk",
                 cancelClass: "testCancel"
             });
         });
         return <div>content</div>;
     }
     let options = {
         header: "test title",
         // footer: "test footer",
         content: Content,
         size: "md",
         cbList: [closeModal],
         close: closeModal,
         // hideBackdrop: true,
         closeByBackDrop: true
     };
     let modal = ZenModal.loadModal(options);
     // let modal = useModal(options);
     modal.show();
     */
    loadModal: function(
        options = { title: "", footer: "", content: "", cbList: [] }
    ) {
        if (!Uts.isObject(options)) {
            alert("modal must be init by object config");
            return false;
        }
        options.$$index = ZenModal.indexCount + 3;
        options.passParams = function(value) {
            options.params = value;
        };
        options.getParams = function() {
            return options.params;
        };
        options.passData = function(value) {
            options._data = value;
        };
        options.passFC = function(value) {
            if (Uts.isObject(value)) {
                for (let prop in value) {
                    if (!options["_FC" + prop]) {
                        options["_FC" + prop] = value[prop];
                    }
                }
            }
        };

        options.execFC = function(fcName, value) {
            options["_FC" + fcName] && options["_FC" + fcName](value);
        };
        let preConfig = StateApi.getStoreState("zenModalConfig");
        preConfig.modalList.push(options);
        StateApi.updateStoreState("zenModalConfig", preConfig);
        options.changeFooterClass = function(value) {
            options._FCfooter && options._FCfooter(value);
            // options.footerClass = value;
            // let newValue = Uts.copyObj(preConfig);
            // StateApi.updateStoreState("zenModalConfig", newValue);
        };
        return {
            show: (function(config, modal) {
                return function() {
                    modal.isShow = true;
                    let newValue = Uts.copyObj(config);
                    StateApi.updateStoreState("zenModalConfig", newValue);
                };
            })(preConfig, options),
            hide: (function(config, modal) {
                return function() {
                    options.isShow = false;
                    let newValue = Uts.copyObj(config);
                    StateApi.updateStoreState("zenModalConfig", newValue);
                };
            })(preConfig, options),
            remove: (function(config, modal) {
                return function() {
                    let index = Uts.findObjByCondition(
                        preConfig.modalList,
                        { $$index: options.$$index },
                        false,
                        true
                    );
                    preConfig.modalList.splice(index, 1);
                    let newValue = Uts.copyObj(preConfig);
                    StateApi.updateStoreState("zenModalConfig", newValue);
                };
            })(preConfig, options)
        };
    }
};

export default ZenModal;

export function useModal(
    options = { title: "", footer: "", content: "", cbList: [] }
) {
    let modal = ZenModal.loadModal(options);
    React.useEffect(() => {
        return modal.remove;
    });
    return modal;
}
